<template>
    <div class="app-container">
      <el-form :inline="true">
        <el-form-item label="名称">
        <el-input
          v-model="queryParams.formName"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="queryParams.startTime"
            type="datetime"
            placeholder="开始时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="startDatePicker"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="queryParams.endTime"
            type="datetime"
            placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="endDatePicker"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
       
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['apply:list']"
          >删除
          </el-button>
          <el-button size="mini"
                     type="primary"
                     icon="el-icon-edit"
                     @click="dialogOpen()"
                     v-hasPermi="['category:update']"
          >录入数据格式说明
          </el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="templateList"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60" align="center"/>
        <el-table-column prop="formName" label="模板标题" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="deleted" label="状态">
          <template slot-scope="scope">{{ scope.row.deleted === '0' ? '生效中' : '已失效' }}</template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="download(scope.row)"
                     v-hasPermi="['category:update']"
          >下载Excel模板
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['category:update']"
                     v-if="scope.row.deleted==='0'"
          >修改
          </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['apply:list']"
            >删除
            </el-button>
            <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="uploadOpen(scope.row)"
                     v-hasPermi="['category:update']"
          >录入数据
          </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <el-dialog :visible.sync="open3">
        <el-upload
          action=""
          :http-request="submitUpload"
          accept=".json"
          ref='upload'
          :file-list="fileList"
          :limit="1">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传json文件，且不超过5MB</div>
          <div slot="tip" class="el-upload-list__item-name">{{fileName}}</div>
        </el-upload>
       
      </el-dialog>
      <!-- 添加或修改菜单对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="模板标题" prop="formName">
                <el-input v-model="form.formName" placeholder="请输入标题"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="模板json" prop="formJson">
                <el-input type="textarea" v-model="form.formJson" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="创建时间" prop="createTime">
                <el-input  v-model="form.createTime" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 对话框 -->
      <el-dialog :title="title2" :visible.sync="open2" width="600px" append-to-body>
        <div>
          仅支持json格式数据,比如
          [{
    "username": "hhh",
    "age": "23"},{
    "username": "hhh",
    "age": "23"}]
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
    import {queryList,download, add, deleteTemplate, update,uploadJson} from "@/api/tools/template";
    import {deepClone} from "@/utils/index";
  
    export default {
      name: "task",
      data() {
        return {
          // 遮罩层
          loading: true,
          // 选中数组
          ids: [],
          // 非单个禁用
          single: true,
          // 非多个禁用
          multiple: true,
          modelVisible: false,
          modelerUrl: '',
          fileName: '',
          tid: '',
          // 表格树数据
          templateList: [],
          dataFile: '',
          fileList: [],
          // 菜单树选项
          menuOptions: [],
          categoryList: [],
          // 弹出层标题
          title: "",
          title2: "说明",
          // 是否显示弹出层
          open: false,
          open2: false,
          open3: false,
          // 总条数
          total: 0,
          // 查询参数
          queryParams: {
            pageNo: 1,
            pageSize: 10,
            startTime: '',
            endTime: '',
            formName: '',
            id: ''
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {
            startTime: [
              {required: true, message: "开始时间不能为空", trigger: "blur"}
            ],
            formName: [
              { type: 'string',required: true, message: '请输入模板标题', trigger: 'blur'},
              { min: 1,max: 30, message: "名称长度在1到30个字符"}
            ]
          },
          startDatePicker: this.beginDate(),
          endDatePicker: this.processDate()
        };
      },
      created() {
        this.getList();
      },
      watch:{
        total(val,oldVal){
          /*  第N页最后一条数据删除后 重新加载上一页 */
          if(this.total>0 && this.total%this.queryParams.pageSize === 0){
            this.queryParams.pageNo = this.queryParams.pageNo - 1
            this.getList(this.queryParams)
          }
        }
      },
      methods: {
        beginDate(){
              return {
                  disabledDate: time =>{
                  if (this.endTime) {
                     return new Date(this.endTime).getTime()> time.getTime()
                      
                  } else {
                      return time.getTime() > Date.now()
                  }
                  }
              }
          },
          processDate() {
              return {
                  disabledDate: time =>{
                  if (this.startTime) {
                      return new Date(this.startTime).getTime() < time.getTime()
                          
                  } else {
                      return time.getTime() > Date.now()
                  }
                  }
              }
          },
        getList() {
          this.loading = true;
          queryList(this.queryParams).then(response => {
            this.templateList = response.data;
            this.total = response.page.total;
            this.loading = false;
          });
        },
        // 取消按钮
        cancel() {
          this.open = false;
          this.reset();
        },
        // 表单重置
        reset() {
          this.form = {
            formJson: '',
            formName: '',
            remark: ''
          };
          this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNo = 1
          this.getList();
        },
        /** 新增按钮操作 */
        handleAdd() {
          this.reset();
          this.form.id = '';
          this.open = true;
          this.title = "添加任务";
        },
        dialogOpen(){
          this.title2 = "说明";
          this.open2 = true;
        },
        uploadOpen(obj){
          this.open3 = true;
          this.tid = obj.id;
        },
        handleChange(upload) {
          //this.fileList=[];
           // this.fileList.push(file);
           // console.log(this.fileList)
           let reader = new FileReader()
        reader.readAsDataURL(upload.file)
        var fileName = upload.file.name;
        var data = {};
        var that = this
        reader.onload = ()=>{

          data = {"file":reader.result,"fileName":fileName,"tid":this.tid};
          this.dataFile = data;
        }
        },
        importJson() {
          //this.empty();
          //this.drawingList = "";
        },
        submitUpload(upload){
          
          let fd = new FormData();
          fd.append("tid",this.tid);
          
          this.fileList.forEach(item=>{

            console.log("文件为:"+item+",文件名:"+item.fileName);
          fd.append("file",item.raw);
          })

          let reader = new FileReader()
        reader.readAsDataURL(upload.file)
        var fileName = upload.file.name;
        var data = {};
        var that = this
        reader.onload = ()=>{

          data = {"file":reader.result,"tid":this.tid};
          //上传
          that.uploading = true
          uploadJson(data).then(function(response){
              console.log(response)
            
                //成功处理
              that.$message.success("导入数据成功")
              that.uploading = false
              that.$refs.upload.clearFiles()
              that.open3=false;    
              const link = document.createElement('a');  //创建a标签
              const blob = new Blob([response], { type: 'application/vnd.ms-excel' });//设置文件流
              link.style.display = 'none';
              // 设置连接
              link.href = URL.createObjectURL(blob);  //将文件流转化为blob地址
              link.download = '数据报表';
              document.body.appendChild(link);
              // 模拟点击事件
              link.click();  //设置点击事件
          },err=>{
              that.uploading = false
              that.$message.error("上传失败")
          })
        }
      
        },
        handleBeforeUpload(file){
          const extension = file.name.split('.')[1] === 'json'
          const isLt2M = file.size / 1024 / 1024 < 5
          if (!extension) {
            this.$message.warning('上传模板只能是json格式!')
            return false
          }
          if (!isLt2M) {
          this.$message.warning('上传模板大小不能超过 5MB!')
          return
          }
          this.fileName = "上传文件名:".concat(file.name);
          this.fileList.push(file);
          return false
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
          this.reset();
          this.form = deepClone(row);
          this.open = true;
          this.title = "修改模板";
        },
        /** 下载操作 */
        download(row) {
          console.log(row.id);
          download(row.id).then(result=>{
            
            const link = document.createElement('a');  //创建a标签
            const blob = new Blob([result], { type: 'application/vnd.ms-excel' });//设置文件流
            link.style.display = 'none';
            // 设置连接
            link.href = URL.createObjectURL(blob);  //将文件流转化为blob地址
            link.download = '数据报表';
            document.body.appendChild(link);
            // 模拟点击事件
            link.click();  //设置点击事件

          }).catch(err=>{
            console.log(err);
          })
        },
        /** 提交按钮 */
        submitForm: function () {
          this.$refs["form"].validate(valid => {
            if (valid) {
              if (this.form.id !== '') {
                update(this.form).then(response => {
                  if (response.code === 0) {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  }
                });
              } else {
                add(this.form).then(response => {
                  if (response.code === 0) {
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  }
                });
              }
            }
          });
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.ids = selection.map(item => item.id);
          this.single = selection.length !== 1;
          this.multiple = !selection.length;
        },
        /** 删除按钮操作 */
        handleDelete(row) {
          let dictIds = [];
          if (row.id) {
            dictIds.push(row.id);
          } else {
            dictIds = this.ids
          }
          this.$confirm('是否确认删除?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function () {
            return deleteTemplate({'ids' : dictIds});
          }).then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          }).catch(function () {
          });
        }
      }
    };
  </script>
  